#include "photofield.h"
#include <qplugin.h>
#include <QGridLayout>
#include <QFileDialog>
#include <QMessageBox>
#include <QApplication>
#include <QBuffer>
#include <QDebug>

PhotoField::PhotoField()
{
    m_id = 0;
}

QWidget *PhotoField::createDelegate(const QVariantMap &properties)
{
    Q_UNUSED(properties)
    QLabel *label = new QLabel();
    m_labels.push_back(label);
    label->setPixmap(QPixmap(":/images/human.png"));
    m_clearButton = new QPushButton(tr("Clear"));
    m_editButton = new QPushButton(tr("Edit"));
    connect(m_clearButton, SIGNAL(clicked()),
            this, SLOT(clearPhoto()));
    connect(m_editButton, SIGNAL(clicked()),
            this, SLOT(editPhoto()));

    QGridLayout *lay = new QGridLayout;
    lay->addWidget(label, 0, 0, 1, 3, Qt::AlignHCenter);
    lay->addWidget(m_editButton, 1, 0, 1, 1);
    lay->addWidget(m_clearButton, 1, 1, 1, 1);
    lay->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 1, 2, 1, 1);

    QWidget *widget = new QWidget;
    widget->setLayout(lay);

    return widget;
}

void PhotoField::setEditable(QWidget *delegate, bool editable)
{
    Q_UNUSED(delegate)
    m_editButton->setEnabled(editable);
    m_clearButton->setEnabled(editable);
}

QVariant PhotoField::data(QWidget *delegate) const
{
    Q_UNUSED(delegate)
    return m_id;
}

void PhotoField::setData(QWidget *delegate, const QVariant &data)
{
    Q_UNUSED(delegate)
    sql.exec(QString("SELECT `data` FROM `photos` WHERE `id`='%1'").arg(data.toInt()));
    m_id = data.toInt();

    if(sql.next()) {
        QByteArray array = sql.value(0).toByteArray();
        foreach(QLabel *label, m_labels)
            label->setPixmap(QPixmap::fromImage(QImage::fromData(array)));
        qDebug() << "Photo found";
    } else {
        foreach(QLabel *label, m_labels)
            label->setPixmap(QPixmap(":/images/human.png"));
        qDebug() << "Photo not found";
    }
}

void PhotoField::clear(QWidget *delegate)
{
    Q_UNUSED(delegate)
    foreach(QLabel *label, m_labels)
        label->setPixmap(QPixmap(":/images/human.png"));
}

void PhotoField::clearPhoto()
{
    if (m_id == 0)
        return;
    if (sql.exec(QString("DELETE FROM `photos` WHERE `id`='%1' LIMIT 1;").arg(m_id))) {
        foreach(QLabel *label, m_labels)
            label->setPixmap(QPixmap(":/images/human.png"));
        m_id = 0;
        QMessageBox::information(0, tr("Information"), tr("Photo removed"));
    } else {
        qWarning() << "Can't delete photo" << m_id;
        QMessageBox::warning(0, tr("Warning"), tr("Photo can't be removed"));
    }
}

void PhotoField::editPhoto()
{
    QString file = QFileDialog::getOpenFileName(0, tr("Chose photo..."), "",
                                                "Images (*.jpg *.jpeg *.png *.gif *.ico)");
    QPixmap pix;
    if(!pix.load(file)) {
        QMessageBox::warning(0, tr("Warning"), tr("Can't load image!"));
        return;
    }

    foreach(QLabel *label, m_labels)
        label->setPixmap(pix);

    qApp->processEvents();

    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    m_labels[0]->pixmap()->save(&buffer, "PNG");

    sql.exec(QString("SELECT `id` FROM `photos` WHERE `id`='%1'").arg(m_id));

    if(sql.next()) { // существует - обновляем
        sql.prepare(QString("UPDATE `photos` SET `data`=:data WHERE `id`='%1'").arg(m_id));
        sql.bindValue(":data", buffer.data());
        sql.exec();
    } else { // нету - вставляем
        sql.prepare(QString("INSERT INTO `photos` (`id`,`data`) VALUES (:id,:data)"));
        sql.bindValue(":id", m_id);
        sql.bindValue(":data", buffer.data());
        sql.exec();
        m_id = sql.lastInsertId().toInt();
    }
}

Q_EXPORT_PLUGIN2(text-field, PhotoField)
